package view;

import com.itextpdf.text.Document;
import com.itextpdf.text.DocumentException;
import com.itextpdf.text.Paragraph;
import com.itextpdf.text.pdf.PdfPCell;
import com.itextpdf.text.pdf.PdfPTable;
import com.itextpdf.text.pdf.PdfWriter;
import controller.GerarRelatorio;
import java.io.FileOutputStream;
import java.io.IOException;
import java.math.BigDecimal;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.swing.JFileChooser;
import javax.swing.JOptionPane;
import javax.swing.filechooser.FileNameExtensionFilter;

public class TelaRelatorio extends javax.swing.JFrame {

    public TelaRelatorio() {
        initComponents();
    }

    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        jScrollPane2 = new javax.swing.JScrollPane();
        jSaidaTabela = new javax.swing.JTable();
        jInicioLabel = new javax.swing.JLabel();
        jFimLabel = new javax.swing.JLabel();
        jSaldoLabel = new javax.swing.JLabel();
        jSaldo = new javax.swing.JTextField();
        jDataInicio = new com.toedter.calendar.JDateChooser();
        jDataFim = new com.toedter.calendar.JDateChooser();
        jPesquisa = new javax.swing.JButton();
        jButton1 = new javax.swing.JButton();

        setDefaultCloseOperation(javax.swing.WindowConstants.DISPOSE_ON_CLOSE);
        setResizable(false);

        jSaidaTabela.setModel(new javax.swing.table.DefaultTableModel(
            new Object [][] {
                {},
                {},
                {},
                {}
            },
            new String [] {

            }
        ));
        jScrollPane2.setViewportView(jSaidaTabela);

        jInicioLabel.setText("data inicio:");

        jFimLabel.setText("data fim:");

        jSaldoLabel.setText("Saldo deste tempo:");

        jSaldo.setEditable(false);
        jSaldo.setBackground(new java.awt.Color(255, 255, 255));

        jPesquisa.setIcon(new javax.swing.ImageIcon(getClass().getResource("/icons/zoom.png"))); // NOI18N
        jPesquisa.setText("Pesquisar");
        jPesquisa.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jPesquisaActionPerformed(evt);
            }
        });

        jButton1.setIcon(new javax.swing.ImageIcon(getClass().getResource("/icons/page_white_acrobat.png"))); // NOI18N
        jButton1.setText("Exporta PDF");
        jButton1.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButton1ActionPerformed(evt);
            }
        });

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(jScrollPane2)
                    .addGroup(layout.createSequentialGroup()
                        .addComponent(jInicioLabel)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(jDataInicio, javax.swing.GroupLayout.PREFERRED_SIZE, 135, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                        .addComponent(jFimLabel)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
                            .addComponent(jButton1)
                            .addGroup(layout.createSequentialGroup()
                                .addComponent(jDataFim, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                                .addComponent(jPesquisa)
                                .addGap(45, 45, 45)
                                .addComponent(jSaldoLabel)
                                .addGap(28, 28, 28)
                                .addComponent(jSaldo, javax.swing.GroupLayout.PREFERRED_SIZE, 60, javax.swing.GroupLayout.PREFERRED_SIZE)))
                        .addGap(0, 0, Short.MAX_VALUE)))
                .addContainerGap())
        );

        layout.linkSize(javax.swing.SwingConstants.HORIZONTAL, new java.awt.Component[] {jDataFim, jDataInicio});

        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
                    .addGroup(layout.createSequentialGroup()
                        .addComponent(jButton1)
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addGroup(layout.createSequentialGroup()
                                .addGap(24, 24, 24)
                                .addComponent(jInicioLabel))
                            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
                                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                                    .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                                        .addComponent(jSaldoLabel)
                                        .addComponent(jSaldo, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                                        .addComponent(jPesquisa))
                                    .addComponent(jDataFim, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.PREFERRED_SIZE, 20, javax.swing.GroupLayout.PREFERRED_SIZE)
                                    .addComponent(jFimLabel, javax.swing.GroupLayout.Alignment.TRAILING)))))
                    .addComponent(jDataInicio, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(jScrollPane2, javax.swing.GroupLayout.DEFAULT_SIZE, 236, Short.MAX_VALUE))
        );

        setSize(new java.awt.Dimension(756, 355));
        setLocationRelativeTo(null);
    }// </editor-fold>//GEN-END:initComponents

    private void jPesquisaActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jPesquisaActionPerformed
        try {
            float total = 0;
            GerarRelatorio gerarRel = new GerarRelatorio();
            gerarRel.query0(jDataInicio.getDate(), jDataFim.getDate());
            this.jSaidaTabela.setModel(gerarRel.gerarRelatorio.tabArquivo);
            for (int i = 0; i < gerarRel.gerarRelatorio.tabArquivo.getRowCount(); i++) {
                total += Float.parseFloat(gerarRel.gerarRelatorio.tabArquivo.getValueAt(i, 1).toString());
            }
            BigDecimal arredonda = new BigDecimal(total);
            arredonda = arredonda.setScale(2, BigDecimal.ROUND_HALF_UP);
            jSaldo.setText(arredonda.toString());
        } catch (SQLException ex) {
            Logger.getLogger(TelaRelatorio.class.getName()).log(Level.SEVERE, null, ex);
        }
    }//GEN-LAST:event_jPesquisaActionPerformed

    private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton1ActionPerformed
        if (jSaidaTabela.getRowCount() > 0) {

            JFileChooser chooser = new JFileChooser();
            chooser.setFileFilter(new FileNameExtensionFilter("PDF", "pdf"));
            chooser.showSaveDialog(null);

            // criação do documento
            Document document = new Document();
            try {

                PdfWriter.getInstance(document, new FileOutputStream(chooser.getSelectedFile() + ".pdf"));
                document.open();

                // Criando uma tabela com N colunas
                PdfPTable table = new PdfPTable(this.jSaidaTabela.getColumnCount());

                // Título para a tabela
                Paragraph tableHeader = null;

                boolean validInicio = true;
                boolean validFim = true;

                if (jDataInicio.getDate() == null) {    // data de inicio e vazio
                    validInicio = false;
                }
                if (jDataFim.getDate() == null) {       // data de fim e vazio
                    validFim = false;
                }
                String dataInicio = "";
                String dataFim = "";
                if (validInicio && validFim) {
                    dataInicio += jDataInicio.getDate().getYear() + 1900 + "-";
                    dataInicio += jDataInicio.getDate().getMonth() + 1 + "-";
                    dataInicio += jDataInicio.getDate().getDate();
                    dataFim += jDataFim.getDate().getYear() + 1900 + "-";
                    dataFim += jDataFim.getDate().getMonth() + 1 + "-";
                    dataFim += jDataFim.getDate().getDate();
                    tableHeader = new Paragraph("Extrado de " + dataInicio + " até " + dataFim);
                }
                if (validInicio && !validFim) {
                    dataInicio += jDataInicio.getDate().getYear() + 1900 + "-";
                    dataInicio += jDataInicio.getDate().getMonth() + 1 + "-";
                    dataInicio += jDataInicio.getDate().getDate();
                    tableHeader = new Paragraph("Extrado a partir de " + dataInicio);
                }
                if (!validInicio && !validFim) {
                    tableHeader = new Paragraph("Extrado");
                }
                if (!validInicio && validFim) {
                    dataFim += jDataFim.getDate().getYear() + 1900 + "-";
                    dataFim += jDataFim.getDate().getMonth() + 1 + "-";
                    dataFim += jDataFim.getDate().getDate();
                    tableHeader = new Paragraph("Extrado até " + dataFim);
                }

                PdfPCell header = new PdfPCell(tableHeader);
                // Definindo que o header vai ocupar as 3 colunas
                header.setColspan(this.jSaidaTabela.getColumnCount());
                // Definindo alinhamento do header
                header.setHorizontalAlignment(Paragraph.ALIGN_CENTER);
                // Adicionando o header à tabela
                table.addCell(header);

                List<String> list = new ArrayList<String>();

                for (int i = 0; i < jSaidaTabela.getColumnCount(); i++) {
                    list.add(jSaidaTabela.getColumnName(i).toString());
                }

                for (int i = 0; i < jSaidaTabela.getRowCount(); i++) {
                    for (int j = 0; j < jSaidaTabela.getColumnCount(); j++) {
                        list.add(jSaidaTabela.getValueAt(i, j).toString());
                    }
                }

                list.add("");
                list.add("Total: " + jSaldo.getText());
                list.add("");

                for (String s : list) {
                    table.addCell(s);
                }

                document.add(table);

                JOptionPane.showMessageDialog(null, "Relatório exportado com sucesso !!!");
            } catch (DocumentException de) {
                System.err.println(de.getMessage());
            } catch (IOException ioe) {
                System.err.println(ioe.getMessage());
            }
            document.close();
        }
    }//GEN-LAST:event_jButton1ActionPerformed

    /**
     * @param args the command line arguments
     */
    public static void main(String args[]) {
        /* Set the Nimbus look and feel */
        //<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
        /* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel.
         * For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html 
         */
        try {
            for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
                if ("Nimbus".equals(info.getName())) {
                    javax.swing.UIManager.setLookAndFeel(info.getClassName());
                    break;
                }
            }
        } catch (ClassNotFoundException ex) {
            java.util.logging.Logger.getLogger(TelaRelatorio.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (InstantiationException ex) {
            java.util.logging.Logger.getLogger(TelaRelatorio.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (IllegalAccessException ex) {
            java.util.logging.Logger.getLogger(TelaRelatorio.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (javax.swing.UnsupportedLookAndFeelException ex) {
            java.util.logging.Logger.getLogger(TelaRelatorio.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        }
        //</editor-fold>
        //</editor-fold>
        //</editor-fold>
        //</editor-fold>

        /* Create and display the form */
        java.awt.EventQueue.invokeLater(new Runnable() {
            public void run() {
//                new RelatorioDiario().setVisible(true);
            }
        });
    }


    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JButton jButton1;
    private com.toedter.calendar.JDateChooser jDataFim;
    private com.toedter.calendar.JDateChooser jDataInicio;
    private javax.swing.JLabel jFimLabel;
    private javax.swing.JLabel jInicioLabel;
    private javax.swing.JButton jPesquisa;
    private javax.swing.JTable jSaidaTabela;
    private javax.swing.JTextField jSaldo;
    private javax.swing.JLabel jSaldoLabel;
    private javax.swing.JScrollPane jScrollPane2;
    // End of variables declaration//GEN-END:variables
}
